package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.product.api.domain.vo.CategoryTreeVo;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author lee
 * @since 2024-07-13
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public List<Category> treeSelect(Integer parentId) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, parentId);
        List<Category> categoryList = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(item -> {
                Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, item.getId()));
                if (count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }
            });
        }
        return categoryList;
    }

    @Override
    public String importCategory(List<Category> categoryList, boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(categoryList) || categoryList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Category category : categoryList) {
            try {
                // 验证是否存在这个用户
                Category c = baseMapper.selectById(category.getId());
                if (StringUtils.isNull(c)) {
                    category.setCreateBy(operName);
                    baseMapper.insert(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品分类 " + category.getId() + " 导入成功");
                } else if (isUpdateSupport) {
                    category.setUpdateBy(operName);
                    baseMapper.updateById(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、商品分类 " + category.getId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、商品分类 " + category.getId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、商品分类 " + category.getId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<CategoryVo> getOneCategory() {

        return baseMapper.getOneCategory();
    }

    @Override
    public List<CategoryTreeVo> getCategoryTree() {
        List<CategoryTreeVo> categoryTreeVoList = baseMapper.selectAllCategory();
        for (CategoryTreeVo categoryTreeVo : categoryTreeVoList) {
            if (categoryTreeVo.getParentId() == 0){
                findAndAddChildren(categoryTreeVo, categoryTreeVoList);
            }
        }
        return categoryTreeVoList;
    }

    private void findAndAddChildren(CategoryTreeVo categoryTreeVo,List<CategoryTreeVo> categoryTreeVoList){
        for (CategoryTreeVo treeVo : categoryTreeVoList) {
            if (treeVo.getParentId()==categoryTreeVo.getId()){
                findAndAddChildren(treeVo,categoryTreeVoList);
                categoryTreeVo.getChildren().add(treeVo);
            }
        }
    }

}
